package com.itheima.service;

import com.itheima.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SpringSecurityUserService2 implements UserDetailsService {

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    //模拟数据库中的用户数据
    private Map<String, User> map = new HashMap<>();

    public void initUserData() {
        User user1 = new User();
        user1.setUsername("admin");
        user1.setPassword(passwordEncoder.encode("admin"));//使用bcrypt提供的方法对密码进行加密

        User user2 = new User();
        user2.setUsername("xiaoming");
        user2.setPassword(passwordEncoder.encode("1234"));

        map.put(user1.getUsername(), user1);
        map.put(user2.getUsername(), user2);
    }


    //根据用户名加载用户数据
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        initUserData();

        System.out.println("用户名:" + username);
        //根据用户名查询数据库获得用户信息(包含密码信息)
        User user = map.get(username);//模拟查询数据库
        if (user == null) {
            //用户名不存在
            return null;
        } else {
            //将用户信息返回给框架,框架帮我们进行比对(页面提交的密码和数据库中的密码)
            List<GrantedAuthority> list = new ArrayList<>();//这个集合封装了该用户的权限
            //我们需要动态的为该用户授权,后期需要改为从数据库中查找对应的权限
            //这个框架约定了,小写的就是权限,大写的就是角色
            list.add(new SimpleGrantedAuthority("permission_A"));//授权
            list.add(new SimpleGrantedAuthority("permission_B"));

            if (username.equals("xiaoming")){
                //给小明加一个余凯琦权限
                list.add(new SimpleGrantedAuthority("yukaiqi"));
            }

            if (username.equals("admin")) {
                //只有admin这个用户才有这个角色
                list.add(new SimpleGrantedAuthority("ROLE_ADMIN"));//授予角色
                list.add(new SimpleGrantedAuthority("add"));//授予权限
            }

            org.springframework.security.core.userdetails.User
                    securityUser = new org.springframework.security.core.userdetails.User(username, user.getPassword(), list);
            return securityUser;
        }
    }
}
